//
//  TutorController.m
//  <21.1> TypingTutor
//
//  Created by chen on 16/9/21.
//  Copyright © 2016年 tyrad. All rights reserved.
//

#import "TutorController.h"

@implementation TutorController

- (instancetype)init
{
    self = [super init];
    if (self) {
        _letter = @[@"a",@"s",@"d",@"f",@"g",@"h",@"j"];
        _timeLimit = 5 ;
    }
    return self;
}


- (void)awakeFromNib{
    [super awakeFromNib];
    [self showAnotherLetter];
    
    [self addObserver:self forKeyPath:@"elapsedTime" options:NSKeyValueObservingOptionNew context:nil];
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSKeyValueChangeKey,id> *)change
                       context:(void *)context{

//    id newValue = [change objectForKey:NSKeyValueObservingOptionNew];

    NSLog(@"`````` %@",change);
    
    double newValue = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
    
    [self.slider setDoubleValue:newValue*20];
    
}






- (void)showAnotherLetter {
    
    //选择随机数，知道得到一个不同的值
    NSInteger x = _lastIndex ;
    while (x == _lastIndex) {
        x = random()%[_letter count];
    }
    _lastIndex = x  ;
    [_outLetterView setMyString:_letter[x]];
    
    //再次计数
    [self resetElapsedTime];
}


- (IBAction)stopGo:(id)sender{
    
    [self resetElapsedTime];
    
    if (_timer == nil) {
        NSLog(@"start timer...");
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(checkThem:) userInfo:nil repeats:YES];
    }else{
        
        [_timer invalidate];
        _timer = nil ;
    }
}

- (void)checkThem:(NSTimer *)timer{
    
    if ([[_inLetterView myString] isEqualToString:[_outLetterView myString]]) {
        [self showAnotherLetter];
    }
    [self updateElapsedTime];
    if (_elapsedTime >= _timeLimit) {
        NSBeep() ;
        [self resetElapsedTime];
    }
    
}


- (void)updateElapsedTime{
    [self willChangeValueForKey:@"elapsedTime"];
    _elapsedTime = [NSDate timeIntervalSinceReferenceDate] - _startTime;
    [self didChangeValueForKey:@"elapsedTime"];
}

- (void)resetElapsedTime {
    _startTime = [NSDate timeIntervalSinceReferenceDate];
    [self updateElapsedTime];
}







@end
